//-----------------------------------------------------------------------------
//クラス名：Upload.java
//所    属：H3A1 04
//名    前：大瀬碩
//説    明：クラブ画像変更機能
//-----------------------------------------------------------------------------
package club;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;


//@WebServlet("/Upload")
@MultipartConfig(location = "C:/tmp/")
public class Upload extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    
    public Upload() {
        super();
        
    }
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		
		//クラブの画像を上書き保存する
		String i = (String) session.getAttribute("sel_club");
		int j = Integer.parseInt(i)-1;
		String[] club = {"futsal","baseball","tennis","soft_tennis","badminton","table_tennis",
						"programming","qualification","light_music","cinema","reading","gardening"};
		Part part = request.getPart("file");
		String name = this.getFileName(part);
		if(this.isValidFile(name)){
			part.write(getServletContext().getRealPath("/images")+"/"+club[j]+".png");
			response.sendRedirect("ClubEdit.jsp");
		}else{
			response.getWriter().println("Invalid file is uploaded.");
		}
	}
	
	//元のファイル名を取得
	private String getFileName(Part part){
		String result = null;
		
		for(String disp : part.getHeader("Content-Disposition").split(";")){
			disp = disp.trim();
			if(disp.startsWith("filename")){
				result = disp.substring(disp.indexOf("=") +1).trim();
				result = result.replace("\"", "").replace("\\","/");
				int pos = result.lastIndexOf("/");
				if(pos >= 0){
					result = result.substring(pos+1);
				}
				break;
			}
		}
		return result;
	}
	
	private boolean isValidFile(String name){
		if(name != null){
			String[] perms = {"gif" , "jpg" , "jpeg" , "png"};
			String[] names = name.split("\\.");
			for(String perm: perms){
				if(perm.equals(names[names.length - 1])){
					return true;
				}
			}
		}
		return false;
	}
}
